package com.sky.aop;

import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFill {
    @Pointcut(" execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.anotation.AutoFill)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void preHandel(JoinPoint joinPoint) {
        log.info("开始自动填充");
        //第一步用于获取注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        com.sky.anotation.AutoFill annotation = signature.getMethod().getAnnotation(com.sky.anotation.AutoFill.class);
        OperationType operationType = annotation.value();
        Class<AutoFill> autoFillClass = AutoFill.class;
        //获取参数
        Object[] args = joinPoint.getArgs();
        Object entity = args[0];
        //准备赋值的数据
        LocalDateTime localDateTime = LocalDateTime.now();
        Long id = BaseContext.getCurrentId();

        //判断 update or insert
        if (operationType == OperationType.INSERT) {
            Class<?> aClass = entity.getClass();
            try {
                Method createTime = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method createUser = aClass.getDeclaredMethod(AutoFillConstant.SET_CREATE_USER,Long.class);
                Method updateTime = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME,LocalDateTime.class);
                Method updateUser = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class
                );
                createTime.invoke(entity, localDateTime);
                updateUser.invoke(entity, id);
                createUser.invoke(entity, id);
                updateTime.invoke(entity, localDateTime);
                return;
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        Class<?> aClass = entity.getClass();
        try {
            Method updateTime = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method updateUser = aClass.getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            updateUser.invoke(entity, id);
            updateTime.invoke(entity, localDateTime);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
